package com.nyp.remoter.ejb;

import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.nyp.remoter.entity.Cat;
import com.nyp.remoter.entity.CatDogFight;
import com.nyp.remoter.entity.Dog;
import com.nyp.remoter.entity.User;

@Stateless
public class PetHandlerEJB {
	
	@PersistenceContext
	EntityManager em;
	
	Random rand = new Random(System.currentTimeMillis());
	
	public void createRandomOwners(int num){
		for (int i=0; i<num; i++){
			createRandomOwner();
		}
	}
	
	public void createRandomOwner(){
		int nextInt = rand.nextInt(10000);
		User u = new User();
		u.setName("Mézga " + nextInt);
		u.setMotherName("Mézga Anyja " + nextInt);
		u.setIdNumber(nextInt);
		u.setDateOfBirth(new Date());
		
		int catNum = rand.nextInt(4);
		for(int i=0; i<catNum; i++){
			Cat c = createRandomCat();
			u.getCats().add(c);
			em.persist(c);
		}
		
		int dogNum = rand.nextInt(4);
		for(int i=0; i<dogNum; i++){
			Dog d = createRandomDog();
			u.getDogs().add(d);
			em.persist(d);
		}		
		em.persist(u);
	}

	private Dog createRandomDog() {
		int nextInt = rand.nextInt(10000);
		Dog dog = new Dog();
		dog.setName("Bloki " + nextInt);
		dog.setGoodHouseKeeper(nextInt % 2 == 0);
		return dog;
	}

	private Cat createRandomCat() {
		int nextInt = rand.nextInt(10000);
		Cat cat = new Cat();
		cat.setName("Maffia " + nextInt);
		cat.setLikesPurring(nextInt % 2 == 0);
		return cat;
	}
	
	public void createRandomFights(int num){
		List<Dog> dogs = em.createQuery("select d from Dog d").getResultList();
		List<Cat> cats = em.createQuery("select c from Cat c").getResultList();
		for(int i=0; i<num; i++){
			createRandomFight(dogs, cats);
		}
	}
	
	private void createRandomFight(List<Dog> dogs, List<Cat> cats){
		Dog dog = dogs.get(rand.nextInt(dogs.size()));
		Cat cat = cats.get(rand.nextInt(cats.size()));
		CatDogFight fight = new CatDogFight();
		fight.setCat(cat);
		fight.setDog(dog);
		fight.setDateOfFight(new Date());
		fight.setDurationOfFight(rand.nextLong());
		em.persist(fight);
	}

}
